<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.supplierName" placeholder="供应商名称" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.purchaseOrderCode" placeholder="采购单号" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label>
            <AInput v-model="searchFrom.productName" placeholder="产品名称" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label>
            <AInput v-model="searchFrom.specModel" placeholder="规格型号" allow-clear />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 2])" type="outline" @click="openEdit('新增')">新增</AButton>
          <!-- <tableImp
            imp-url="/produce/erpCustomerImport"
            :file-temp="() => onExport('template')"
          ></tableImp> -->
          <ATooltip
            v-if="isAuth([1, 2])"
            :disabled="!(isEmpty(selectRows) || !!selectRows.find((item) => item.inboundStatus))"
            content="请选择未入库的采购单"
          >
            <AButton
              type="outline"
              status="normal"
              :disabled="isEmpty(selectRows) || !!selectRows.find((item) => item.inboundStatus)"
              :loading="inWarehouseLoad"
              @click="inWarehouse()"
            >
              入库
            </AButton>
          </ATooltip>
          <ATooltip v-if="isAuth([1, 2])" :disabled="!isEmpty(selectRows)" content="请选择采购记录">
            <AButton status="danger" :disabled="isEmpty(selectRows)" @click="batchDel()">
              批量删除
            </AButton>
          </ATooltip>
        </ASpace>
        <ASpace>
          <AButton type="primary" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        ref="tableRef"
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        :row-selection="{ showCheckedAll: true, type: 'checkbox' }"
        :span-method="spanMethod"
        span-all
        column-resizable
        size="small"
        row-key="purchaseOrderDetailId"
        @select="
          (rowKeys: (string | number)[], rowKey: string | number, record: TableData) =>
            tableEvent('select', { rowKeys, rowKey, record })
        "
        @select-all="(checked: boolean) => tableEvent('select-all', checked)"
      >
        <template #columns>
          <ATableColumn title="创建时间" data-index="createdDt" :width="120" align="center">
            <template #cell="{ record }">
              <div>{{ dayjs(record.createdDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn title="采购单号" data-index="purchaseOrderCode" :width="100">
          </ATableColumn>
          <ATableColumn title="供应商" data-index="supplierName" :width="100"> </ATableColumn>
          <ATableColumn title="材料名称" data-index="productName" :width="100"> </ATableColumn>
          <ATableColumn title="规格型号" data-index="specModel" :width="100"> </ATableColumn>
          <ATableColumn title="材质代码" data-index="materialCode" :width="100"> </ATableColumn>
          <ATableColumn title="材质" data-index="materialDesc" :width="100"> </ATableColumn>
          <ATableColumn title="楞型" data-index="fluteType" :width="100"> </ATableColumn>
          <ATableColumn title="压线" data-index="crimpLine" :width="100"> </ATableColumn>
          <ATableColumn title="单位" data-index="unit" :width="100"> </ATableColumn>
          <ATableColumn title="数量" data-index="qty" :width="100"> </ATableColumn>
          <ATableColumn title="单价" data-index="unitPrice" :width="100"> </ATableColumn>
          <ATableColumn title="金额" data-index="amt" :width="100">
            <template #cell="{ record }">
              {{ formatPrice(decimalRound(record.qty! * record.unitPrice!, 4)) }}
            </template>
          </ATableColumn>
          <ATableColumn title="总金额" data-index="totalAmt" :width="100">
            <template #cell="{ record }">
              {{ formatPrice(decimalRound(sumAmt(record), 4)) }}
            </template>
          </ATableColumn>
          <ATableColumn title="含税" data-index="isInclTax" :width="70" align="center">
            <template #cell="{ record }">
              <icon-check-circle-fill v-if="record.isInclTax" style="color: #67c23a" size="20px" />
              <icon-close-circle-fill v-if="!record.isInclTax" style="color: red" size="20px" />
            </template>
          </ATableColumn>
          <ATableColumn title="交货日期" data-index="deliveryDate" :width="120">
            <template #cell="{ record }">
              <div v-if="record.deliveryDate">
                {{ dayjs(record.deliveryDate).format('YYYY-MM-DD') }}
              </div>
            </template>
          </ATableColumn>
          <ATableColumn title="入库" data-index="inboundStatus" :width="80" align="center">
            <template #cell="{ record }">
              <icon-check-circle-fill
                v-if="record.inboundStatus"
                style="color: #67c23a"
                size="20px"
              />
              <icon-close-circle-fill v-if="!record.inboundStatus" style="color: red" size="20px" />
            </template>
          </ATableColumn>
          <ATableColumn title="备注" data-index="remark" :width="155"> </ATableColumn>
          <ATableColumn title="更新时间" :width="155" align="center">
            <template #cell="{ record }">
              <div>{{ dayjs(record.updatedDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn v-if="isAuth([1, 2])" title="操作" :width="150" fixed="right">
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'print')">
                  打印
                </AButton>
              </ASpace>
              <ASpace class="erp-mt-6">
                <AButton type="primary" size="mini" @click="rowEvent(record, 'copy')">
                  复制
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    >
    </EditPopupForm>
    <materialPrint ref="materialPrintRef" :check-data="detailData"></materialPrint>
    <AModal
      v-model:visible="inWarehouseModal"
      title="入库"
      @close="modalEvent('close')"
      @before-ok="(done: any) => modalEvent('ok', { done })"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AForm ref="inWarehouseFormRef" :model="inWarehouseForm" auto-label-width>
        <AFormItem
          label="交货日期"
          field="deliveryDate"
          :rules="[{ required: true, message: '请选择交货日期' }]"
          :validate-trigger="['change', 'blur']"
        >
          <ADatePicker
            v-model="inWarehouseForm.deliveryDate"
            placeholder="交货日期"
            class="w100"
          ></ADatePicker>
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import materialPrint from './print.vue'
import dayjs from 'dayjs'
import { Message, Modal, TableData, TableInstance } from '@arco-design/web-vue'
import {
  batchDelPurchase,
  delPurchase,
  getPurchaseAllList,
  getPurchaseDetail,
  getPurchasePageList,
  purchaseInWarehouse,
  PurchaseInWarehouseReq,
  PurchaseItemHandle,
  PurchaseListSearch,
  PurchaseResItem
} from '@renderer/api/purchasingDep'
import { isEmpty, sum, sumBy } from 'lodash-es'
import { isAuth } from '@renderer/utils/auth'
import { decimalRound, formatPrice } from '@renderer/utils/mixins'
import { deleteNullObject } from '@renderer/utils/data-processing'

const searchFrom = ref<PurchaseListSearch>({})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<PurchaseItemHandle[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const tableRef = ref<TableInstance>()
const materialPrintRef = ref<InstanceType<typeof materialPrint>>() // 打印组件
const detailData = ref<PurchaseResItem>({
  purchaseOrderId: '',
  purchaseOrderCode: '',
  supplierId: '',
  deliveryDate: '',
  supplierName: '',
  supplierAddress: '',
  contactName: '',
  contactPhone: '',
  purchaseAmt: 0,
  isInclTax: 0,
  formType: 0,
  detailList: [],
  createdBy: '',
  createdDt: '',
  updatedBy: '',
  updatedDt: '',
  remark: '',
  inboundStatus: 0
})
const selectRows = ref<PurchaseItemHandle[]>([])
const inWarehouseLoad = ref(false)
const inWarehouseForm = ref({
  deliveryDate: ''
}) // 入库表单
const inWarehouseModal = ref(false) // 入库modal
const inWarehouseFormRef = ref() // 入库表单ref

onMounted(() => {
  getTableData()
})

function sumAmt(rowData: PurchaseResItem) {
  const amts = rowData.detailList.map((item) =>
    Number(decimalRound(item.qty! * item.unitPrice!, 4))
  )
  return sum(amts)
}

function clearTableSelect() {
  tableRef.value?.selectAll(false)
  selectRows.value = []
}

function formatData(baseData: PurchaseResItem[]): any[] {
  return baseData
    .map((item, index) => {
      item.index = index + 1
      if (!isEmpty(item.detailList)) {
        return item.detailList.map((detailItem, index) => {
          if (index === 0) {
            return {
              ...detailItem,
              ...item,
              span: item.detailList.length,
              totalAmt: decimalRound(sumBy(item.detailList, 'amt'), 4)
            }
          } else {
            return { ...detailItem, ...item }
          }
        })
      } else {
        return [item]
      }
    })
    .flat()
}
async function getTableData() {
  searchFrom.value.formType = 0
  const res = await getPurchasePageList(deleteNullObject({ ...searchFrom.value, ...pageParam }))
  tableData.value = formatData(res.data.list)
  pageParam.totalCount = res.data.totalCount!
}

const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 4 || columnIndex > 13) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}
function onReset() {
  searchFrom.value = {}
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function tableEvent(type: 'page-change' | 'select' | 'select-all', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break
    case 'select':
      {
        const { rowKeys, rowKey, record } = param
        if (rowKeys.includes(rowKey)) {
          const temp = record.detailList.map((item) => {
            item.supplierId = record.supplierId
            item.inboundStatus = record.inboundStatus
            return item
          })
          selectRows.value = selectRows.value?.concat(temp)
        } else {
          selectRows.value = selectRows.value?.filter(
            (item) => item.purchaseOrderId != record.purchaseOrderId
          )
        }
        console.log(selectRows.value)
      }
      break
    case 'select-all':
      if (param) {
        selectRows.value = selectRows.value.concat(tableData.value)
      } else {
        const ids = tableData.value.map((item) => item.purchaseOrderDetailId)
        selectRows.value = selectRows.value.filter(
          (item) => !ids.includes(item.purchaseOrderDetailId)
        )
      }
      break
    default:
      break
  }
}

function openEdit(title: string) {
  rowData.value = {}
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref({})
function rowEvent(row: PurchaseResItem, type: 'del' | 'copy' | 'edit' | 'print') {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delPurchase({ purchaseOrderId: row.purchaseOrderId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '复制'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break
    case 'print':
      getPurchaseDetail({ purchaseOrderId: row.purchaseOrderId }).then((res) => {
        detailData.value = res.data
        nextTick(() => {
          materialPrintRef.value?.printInfo()
        })
      })
      break

    default:
      break
  }
}

function batchDel() {
  const idList = selectRows.value.map((item) => item.purchaseOrderId!)
  batchDelPurchase({ idList: idList }).then(() => {
    Message.success('删除成功')
    onSearch()
    clearTableSelect()
  })
}

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  const headerData = [
    { title: '创建时间', value: 'createdDt', width: 180 },
    { title: '采购单号', value: 'purchaseOrderCode', width: 180 },
    { title: '供应商', value: 'supplierName', width: 180 },
    { title: '材料名称', value: 'productName', width: 180 },
    { title: '规格型号', value: 'specModel' },
    { title: '材质代码', value: 'materialCode' },
    { title: '材质', value: 'materialDesc' },
    { title: '楞型', value: 'fluteType' },
    { title: '压线', value: 'crimpLine' },
    { title: '单位', value: 'unit' },
    { title: '数量', value: 'qty' },
    { title: '单价', value: 'unitPrice' },
    { title: '金额', value: 'amt' },
    { title: '含税', value: 'isInclTax' },
    { title: '交货日期', value: 'deliveryDate' },
    { title: '备注', value: 'remark' }
  ]
  let excelData: PurchaseResItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '原材料采购数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getPurchaseAllList(searchFrom.value)
        excelData = formatData(res.data.list)
        excelData = excelData.map((item) => {
          item.isInclTax = item.isInclTax ? '是' : '否q'
          item.inboundStatus = item.inboundStatus ? '是' : '否q'
          item.deliveryDate = item.deliveryDate ? dayjs(item.deliveryDate).format('YYYY-MM-DD') : ''
          item.createdDt = item.createdDt ? dayjs(item.createdDt).format('YYYY-MM-DD') : ''
          return item
        })
      }
      break
    case 'template':
      fileTitle = '原材料采购导入模板'
      excelData = [
        {
          purchaseOrderId: '1883399912876507138',
          purchaseOrderCode: 'PO25012600003',
          supplierId: '1883171413431472130',
          purchaseAmt: 236,
          isInclTax: 0,
          deliveryDate: '2025-01-26',
          formType: 0,
          supplierName: '',
          supplierAddress: '',
          contactName: '',
          contactPhone: '',
          detailList: [],
          createdBy: 'test/模拟用户',
          createdDt: '2025-01-26 14:21:45',
          updatedBy: 'test/模拟用户',
          updatedDt: '2025-01-26 14:21:45',
          remark: '',
          inboundStatus: 0
        }
      ]
      break
    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle)
  })
}

function inWarehouse() {
  if (isEmpty(selectRows.value)) return
  inWarehouseModal.value = true
}

// 弹窗事件
const modalEvent = (type: string, param?: any) => {
  switch (type) {
    case 'ok':
      {
        const { done } = param
        inWarehouseFormRef.value.validate((errors: any) => {
          if (!errors) {
            inWarehouseLoad.value = true
            const apiLists = selectRows.value.map((item) => {
              const reqParam: PurchaseInWarehouseReq = {
                materialName: item.productName,
                supplierId: item.supplierId,
                materialCategory: item.productCategory,
                materialType: 0,
                spec: item.specModel,
                materialCode: item.materialCode,
                materialDesc: item.materialDesc,
                fluteType: item.fluteType,
                crimpLine: item.crimpLine,
                unit: item.unit,
                stockQty: item.qty,
                unitPrice: item.unitPrice,
                purchaseOrderId: item.purchaseOrderId,
                deliveryDate: inWarehouseForm.value.deliveryDate
              }
              return purchaseInWarehouse(reqParam)
            })
            Promise.allSettled(apiLists).then((res) => {
              const errors = res.filter((item) => item.status === 'rejected')
              if (errors.length != 0) {
                Message.warning(`${res.length - errors.length}入库成功，${errors.length}入库失败`)
              } else {
                Message.success('全部入库成功')
              }
              getTableData()
              inWarehouseLoad.value = false
              clearTableSelect()
              done(true)
            })
          } else {
            done(false)
          }
        })
      }
      break
    case 'close':
      inWarehouseFormRef.value.resetFields()
      inWarehouseForm.value = {
        deliveryDate: ''
      }
      inWarehouseModal.value = false
      break
    case 'open':
      break
    case 'cancel':
      inWarehouseFormRef.value.resetFields()
      inWarehouseModal.value = false
      break
    default:
      break
  }
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
